package com.atguigu.yygh.sms.controller;

import com.atguigu.yygh.common.R;
import com.atguigu.yygh.sms.service.SmsService;
import com.atguigu.yygh.sms.utils.RandomUtil;
import com.sun.org.apache.xpath.internal.operations.Bool;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * @Author zhmwi
 * @Date 2021/7/16
 * @Dersciption
 */
@RestController
@Api("发送短信的接口")
@RequestMapping("/api/sms/")
public class SmsController {
    @Autowired
    private SmsService smsService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @ApiOperation("发送短信")
    @GetMapping("/send/{phone}")
    public R sendCode(@PathVariable("phone") String phone){
        //去Redis查一下是否发送过短信
        String redisCode = redisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(redisCode)){
            System.err.println(redisCode);
            //有值 不用发短信啦
            return R.ok();
        }
        //生成验证码
        String code = RandomUtil.getFourBitRandom();
        Boolean isSend = smsService.sendCode(phone,code);
        if (isSend){
            //发送成功 保存到redis一份
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
            return R.ok();
        }else{
            return R.error();
        }
    }
}
